<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="geometry" content="line">
  <link rel="stylesheet" href="./assets/common.css">
  <title>State Driven Charts</title>
</head>
<body>
<div id="canvas1"></div>
<div id="canvas2"></div>
<script src="./assets/jquery-3.2.1.min.js"></script>
<script src="./assets/data-set.min.js"></script>
<script src="../build/g2.js"></script>
<script>
  const data = [
    { gender: 'male', jobCat: 'A', salary: 10000 },
    { gender: 'male', jobCat: 'B', salary: 10000 },
    { gender: 'male', jobCat: 'A', salary: 34400 },
    { gender: 'male', jobCat: 'A', salary: 12000 },
    { gender: 'male', jobCat: 'A', salary: 11111 },
    { gender: 'male', jobCat: 'B', salary: 10000 },
    { gender: 'female', jobCat: 'A', salary: 12333 },
    { gender: 'female', jobCat: 'A', salary: 14000 },
    { gender: 'female', jobCat: 'A', salary: 23400 },
    { gender: 'female', jobCat: 'B', salary: 30000 },
    { gender: 'female', jobCat: 'B', salary: 14000 },
    { gender: 'female', jobCat: 'B', salary: 10030 },
    { gender: 'female', jobCat: 'C', salary: 22222 }
  ];
  const ds = new DataSet({
    state: {
      gender: 'male' // 初始化state值
    }
  });
  const dv1 = ds.createView('main').source(data)
    .transform({
      type: 'aggregate',
      operations: [ 'mean' ], // 求均值
      fields: [ 'salary' ],
      groupBy: [ 'gender' ],
      as: [ 'mean' ]
    });
  const dv2 = ds.createView('detail').source(data)
    .transform({
      type: 'filter',
      callback(row) {
        return row.gender === ds.state.gender; // 过滤数据
      }
    })
    .transform({
      type: 'aggregate',
      operations: [ 'mean' ], // 求均值
      fields: [ 'salary' ],
      groupBy: [ 'jobCat' ],
      as: [ 'mean' ]
    });

  const schema = {
    mean: {
      alias: '平均工资'
    }
  };

  const chart1 = new G2.Chart({
    animate: false,
    container: 'canvas1',
    height: 400
  });
  chart1.source(dv1, schema);
  chart1.interval()
    .position('gender*mean', 'dodge')
    .color('gender');

  chart1.on('click', evt => {
    console.log(evt);
    ds.setState('gender', evt.data._origin.gender); // 更新状态量
  });
  chart1.render();

  const chart2 = new G2.Chart({
    animate: false,
    container: 'canvas2',
    height: 400
  });
  chart2.source(dv2, schema);
  chart2.interval()
    .position('jobCat*mean', 'dodge')
    .color('jobCat');
  chart2.render();
</script>
</body>
</html>
